<template>
  <div class="page-container">
    <!-- 导航栏 -->
    <van-nav-bar title="我的收藏" />

    <!-- 筛选标签 -->
    <van-sticky>
      <div class="filter-tabs">
        <van-tabs v-model:active="activeTab" @change="onTabChange">
          <van-tab title="全部" name="all">
            <span class="tab-count">({{ favoriteWords.length }})</span>
          </van-tab>
          <van-tab title="很陌生" name="unfamiliar">
            <span class="tab-count">({{ unfamiliarWords.length }})</span>
          </van-tab>
          <van-tab title="有印象" name="familiar">
            <span class="tab-count">({{ familiarWords.length }})</span>
          </van-tab>
        </van-tabs>
      </div>
    </van-sticky>

    <!-- 搜索栏 -->
    <div class="search-section">
      <van-search
        v-model="searchValue"
        placeholder="搜索收藏的单词"
        @search="onSearch"
        @clear="onClear"
      />
    </div>

    <!-- 单词列表 -->
    <div class="favorites-content">
      <van-empty v-if="displayWords.length === 0" description="暂无收藏的单词">
        <van-button type="primary" @click="goToHome">去背单词</van-button>
      </van-empty>

      <div v-else class="word-list">
        <!-- 排序选项 -->
        <div class="sort-bar-full">
          <van-dropdown-menu>
            <van-dropdown-item v-model="sortType" :options="sortOptions" />
          </van-dropdown-menu>
        </div>

        <!-- 单词卡片 -->
        <div
          v-for="word in sortedWords"
          :key="word.id"
          class="word-card card"
          @click="goToDetail(word.id)"
        >
          <div class="word-content">
            <div class="word-header">
              <div class="word-info">
                <h3 class="word-title">{{ word.word }}</h3>
                <van-tag
                  :type="getFavoriteLevel(word.id) === 1 ? 'warning' : 'success'"
                  size="small"
                >
                  {{ getFavoriteLevel(word.id) === 1 ? '很陌生' : '有印象' }}
                </van-tag>
              </div>
              <div class="word-actions">
                <van-button
                  size="small"
                  type="danger"
                  @click.stop="removeFavorite(word.id)"
                >
                  取消收藏
                </van-button>
              </div>
            </div>
            <p class="word-pronunciation">{{ word.pronunciation }}</p>
            <p class="word-meaning">{{ word.meaning }}</p>
            <div class="word-meta">
              <span class="meta-item">
                <van-icon name="clock-o" />
                {{ getFavoriteTime(word.id) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 批量操作 -->
    <van-action-bar v-if="favoriteWords.length > 0">
      <van-action-bar-icon
        icon="delete-o"
        text="清空"
        @click="clearAllFavorites"
      />
      <van-action-bar-icon
        icon="share"
        text="导出"
        @click="exportFavorites"
      />
      <van-action-bar-button
        type="primary"
        text="开始复习"
        @click="startReview"
      />
    </van-action-bar>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useWordStore } from '@/stores/word'
import { showToast, showConfirmDialog } from 'vant'

export default {
  name: 'Favorites',
  setup() {
    const router = useRouter()
    const wordStore = useWordStore()
    
    const activeTab = ref('all')
    const searchValue = ref('')
    const sortType = ref('time')
    
    const sortOptions = [
      { text: '收藏时间', value: 'time' },
      { text: '单词字母', value: 'alphabet' },
      { text: '熟悉程度', value: 'level' }
    ]

    // 计算属性
    const { favoriteWords, unfamiliarWords, familiarWords } = wordStore
    
    const displayWords = computed(() => {
      let words = []
      switch (activeTab.value) {
        case 'unfamiliar':
          words = unfamiliarWords
          break
        case 'familiar':
          words = familiarWords
          break
        default:
          words = favoriteWords
      }
      
      // 搜索过滤
      if (searchValue.value) {
        words = words.filter(word => 
          word.word.toLowerCase().includes(searchValue.value.toLowerCase()) ||
          word.meaning.includes(searchValue.value)
        )
      }
      
      return words
    })
    
    const sortedWords = computed(() => {
      const words = [...displayWords.value]
      
      switch (sortType.value) {
        case 'alphabet':
          return words.sort((a, b) => a.word.localeCompare(b.word))
        case 'level':
          return words.sort((a, b) => {
            const levelA = wordStore.getFavoriteLevel(a.id)
            const levelB = wordStore.getFavoriteLevel(b.id)
            return levelA - levelB
          })
        case 'time':
        default:
          return words.sort((a, b) => {
            const timeA = wordStore.favorites.get(a.id)?.timestamp || 0
            const timeB = wordStore.favorites.get(b.id)?.timestamp || 0
            return timeB - timeA // 最新的在前
          })
      }
    })

    // 方法
    const onTabChange = (name) => {
      activeTab.value = name
    }

    const onSearch = (value) => {
      console.log('搜索收藏:', value)
    }

    const onClear = () => {
      searchValue.value = ''
    }

    const goToHome = () => {
      router.push('/home')
    }

    const goToDetail = (id) => {
      router.push(`/word/${id}`)
    }

    const getFavoriteLevel = (wordId) => {
      return wordStore.getFavoriteLevel(wordId)
    }

    const getFavoriteTime = (wordId) => {
      const fav = wordStore.favorites.get(wordId)
      if (fav) {
        return new Date(fav.timestamp).toLocaleDateString()
      }
      return ''
    }

    const removeFavorite = async (wordId) => {
      const result = await showConfirmDialog({
        title: '确认取消收藏',
        message: '确定要取消收藏这个单词吗？'
      })
      
      if (result) {
        wordStore.toggleFavorite(wordId, wordStore.getFavoriteLevel(wordId))
        showToast('已取消收藏')
      }
    }

    const clearAllFavorites = async () => {
      const result = await showConfirmDialog({
        title: '确认清空',
        message: '确定要清空所有收藏吗？此操作不可恢复。'
      })
      
      if (result) {
        favoriteWords.forEach(word => {
          wordStore.favorites.delete(word.id)
        })
        showToast('已清空所有收藏')
      }
    }

    const exportFavorites = () => {
      const data = favoriteWords.map(word => ({
        word: word.word,
        pronunciation: word.pronunciation,
        meaning: word.meaning,
        level: getFavoriteLevel(word.id) === 1 ? '很陌生' : '有印象',
        time: getFavoriteTime(word.id)
      }))
      
      const text = JSON.stringify(data, null, 2)
      const blob = new Blob([text], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `我的单词收藏_${new Date().toLocaleDateString()}.json`
      a.click()
      URL.revokeObjectURL(url)
      
      showToast('导出成功')
    }

    const startReview = () => {
      if (favoriteWords.length === 0) {
        showToast('暂无收藏的单词')
        return
      }
      
      // 随机选择一个收藏的单词开始复习
      const randomWord = favoriteWords[Math.floor(Math.random() * favoriteWords.length)]
      router.push(`/word/${randomWord.id}`)
    }

    // 生命周期
    onMounted(() => {
      if (wordStore.words.length === 0) {
        wordStore.loadWords()
      }
    })

    return {
      activeTab,
      searchValue,
      sortType,
      sortOptions,
      favoriteWords,
      unfamiliarWords,
      familiarWords,
      displayWords,
      sortedWords,
      onTabChange,
      onSearch,
      onClear,
      goToHome,
      goToDetail,
      getFavoriteLevel,
      getFavoriteTime,
      removeFavorite,
      clearAllFavorites,
      exportFavorites,
      startReview
    }
  }
}
</script>

<style scoped>
.filter-tabs {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.van-search{
  margin-top: 8px;
}
/* 调整标签页高度，使其更紧凑 */
.filter-tabs :deep(.van-tabs__wrap) {
  height: 44px;
}

.filter-tabs :deep(.van-tab) {
  height: 44px;
  line-height: 36px;
  padding: 4px 12px;
  font-size: 14px;
}

.filter-tabs :deep(.van-tabs__nav) {
  padding: 0;
}

.filter-tabs :deep(.van-tabs__line) {
  bottom: 2px;
}

/* 隐藏van-tabs自动生成的内容区域 */
.filter-tabs :deep(.van-tabs__content) {
  display: none;
}

.tab-count {
  font-size: 12px;
  color: var(--text-color-3);
  margin-left: 4px;
}

.search-section {
  background: white;
  padding: 0;
}

/* 去除搜索框的上下padding */
.search-section :deep(.van-search) {
  padding-top: 0;
  padding-bottom: 0;
}

.favorites-content {
  padding: 0 2px 80px;
}

.sort-bar-full {
  width: 100%;
  margin-bottom: 12px;
}

.sort-bar-full .van-dropdown-menu {
  width: 100%;
}

.word-list {
  margin-top: 8px;
}

.word-card {
  cursor: pointer;
  padding: 8px 7px;
}
.card{
  margin-top: 0px;
  margin-bottom: 8px;;
}

.word-content {
  padding: 6px;
}

.word-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 4px;
}

.word-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.word-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
  margin: 0;
}

.word-actions {
  display: flex;
  gap: 8px;
}

.word-pronunciation {
  font-size: 14px;
  color: var(--text-color-2);
  margin-bottom: 4px;
  font-style: italic;
}

.word-meaning {
  font-size: 14px;
  color: var(--text-color-3);
  line-height: 1.5;
  margin-bottom: 4px;
}

.word-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: var(--text-color-2);
  padding: 2px 6px;
}

.van-action-bar {
  background: white;
  border-top: 1px solid var(--border-color);
}

/* 通栏下拉菜单样式 */
:deep(.van-dropdown-menu) {
  width: 100%;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

:deep(.van-dropdown-item) {
  width: 100%;
  background: #f8f9fa;
  border-radius: 8px;
}

:deep(.van-dropdown-item__title) {
  color: var(--text-color);
  font-size: 14px;
  font-weight: 500;
  padding: 12px 16px;
  text-align: center;
  width: 100%;
  background: #f8f9fa;
  border-radius: 8px;
}

:deep(.van-dropdown-item__title):hover {
  background: #e9ecef;
}
</style>